package com.tarena.lbs.activity.rpc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.activity.api.ActivityApi;
import com.tarena.lbs.activity.api.pojo.ActivityDto;
import com.tarena.lbs.activity.dao.mapper.ActivityMapper;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.user.api.UserApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@DubboService
public class ActivityApiImpl implements ActivityApi {

    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityMapper activityMapper;
    @DubboReference
    private UserApi userApi;

    @Override
    public Boolean activityVisible(Integer userId, Integer activityId) {
        int i=activityMapper.activityVisible(activityId);
        if (i<0){
            throw new RuntimeException("活动不存在");
        }else{
            //检查活动人群是否为空
            int i1=activityMapper.activityTarget(userId);
            if (i1>0){
                Integer businessId=userApi.getBusinessId(userId);
                //检查用户所属人群
                List<Integer> list=userApi.getUserGroupIds(userId,businessId);
                //活动的活动人群，是String
                ActivityDto activityDto=activityMapper.getActivityDto(activityId);
                String targetCustomer=activityDto.getTargetCustomer();
                boolean isTarget=false;
                //遍历List version2使用while判断String的,是否存在进行分割
                for(Integer number:list){
                    //查看当前List的元素在这个String里存在吗，因为String里是,分割
                    boolean contains = targetCustomer.contains(number+"");
                    if (contains==true){
                        isTarget=true;
                        return true;
                    }else{
                        throw new RuntimeException("用户不是活动的目标人群");
                    }
                }
            }
        }
        return false;
    }

    @Override
    public ActivityDto getActivityById(Integer activityId) {
        //获取活动详情
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("id",activityId);
        ActivityPO activityPO=activityMapper.selectOne(queryWrapper);
        log.debug("activityPO:{}",activityPO);
        ActivityDto activityDto=new ActivityDto();
        BeanUtils.copyProperties(activityPO,activityDto);
       return activityDto;
    }
}
